<template>
  <div>
    <div id="print-wrap">
      <table class="table table-bordered vertical-align-middle text-center" v-loading="loading">
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td>{{ relatedData.customer_name || '' }}</td>
            <td>贷款金额（万元）</td>
            <td>
              <span>{{ contract.reply_funds }}</span>
            </td>
            <td>用款期限（年）</td>
            <td>
              <span class="px-2">{{ contract.load_years || '-' }}</span>
              年
            </td>
          </tr>
          <tr>
            <td>贷款利率</td>
            <td>
              <span class="px-2">{{ contract.load_rate || '-' }}</span>
              %
            </td>
            <td>贷款时间</td>
            <td>
              <span class="px-2">{{ $utils.dateFormat(relatedData.load_date, 'yyyy.MM.dd') }}</span>
            </td>
            <td>到期时间</td>
            <td>
              <span class="px-2">
                {{ $utils.dateFormat(relatedData.load_end_date, 'yyyy.MM.dd') }}
              </span>
            </td>
          </tr>

          <tr>
            <td>银行名称</td>
            <td>{{ relatedData.bank_name }}</td>
            <td>还款付息方式</td>
            <td colspan="3">
              <div v-if="isViewMode" class="row">
                <div class="col d-flex align-items-center">
                  <span>{{ enumRepayType[contract.repay_method] || '-' }}</span>
                </div>
                <div class="col">
                  <el-button @click="showViewRepayList">查看还款计划</el-button>
                </div>
              </div>
              <div class="row" v-else>
                <div class="d-flex align-items-center">
                  <el-radio-group v-model="repayType" @change="onRepayTypeChange">
                    <el-radio v-for="(value, key) in enumRepayType" :label="key" :key="key">
                      {{ value }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div class="col">
                  <el-button @click="showRepayList">生成还款计划</el-button>
                </div>
              </div>
            </td>
          </tr>

          <tr>
            <td :rowspan="1 + warrantFeeRecordCount">担保费率</td>
            <td :rowspan="1 + warrantFeeRecordCount">
              {{ contract.gua_rate || relatedData.gua_rate || '-' }}%
            </td>
            <td :rowspan="1 + warrantFeeRecordCount">
              <div>担保费设置</div>
              <div>(共{{ warrantFeeRecordTotal }}元)</div>
            </td>
            <td colspan="2" class="label-td" v-if="warrantFeeRecordCount">应缴担保费截止时间</td>
            <td class="label-td" v-if="warrantFeeRecordCount">应交担保费（元）</td>
            <td colspan="3" v-if="!warrantFeeRecordCount" class="text-muted">暂无担保费设置</td>
          </tr>

          <template v-if="isViewMode">
            <tr v-for="(wf, index) in warrantFeeRecords" :key="index">
              <td colspan="2">{{ $utils.dateFormat(wf.due_warrant_date, 'yyyy年MM月dd日') }}</td>
              <td>{{ wf.due_warrant_fee }}</td>
            </tr>
          </template>

          <template v-else>
            <tr v-for="(wf, index) in warrantFeeRecords" :key="index">
              <td colspan="2" class="input-td">
                <el-date-picker
                  v-model="wf.due_warrant_date"
                  type="date"
                  placeholder="截止时间"
                  class="w-100"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </td>
              <td class="input-td">
                <div class="d-flex">
                  <input
                    type="number"
                    class="form-control text-center flex-1"
                    placeholder="请填写"
                    v-model="wf.due_warrant_fee"
                  />
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>

    <div class="text-center" v-if="!isViewMode">
      <el-button class="btn-long" type="primary" @click="handlePass">登记</el-button>
      <el-button class="btn-long" type="danger" @click="handleDismiss">取消</el-button>
    </div>

    <repay-plan-dialog
      ref="repay"
      @getData="getRepayList"
      :visible.sync="repayVisible"
      :query-id="relatedId"
      :year="+contract.load_years"
      :view-mode="isViewMode"
      :repay-method="+repayType"
    ></repay-plan-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumRepayType } from '@/credit/plugins/enum'
import warrantFeeRecordMixin from '@/credit/mixin/mission/warrantFeeRecord'
import RepayPlanDialog from '@/credit/components/repay/RepayPlanDialog'
export default {
  components: {
    RepayPlanDialog,
  },
  mixins: [warrantFeeRecordMixin],
  props: {
    viewMode: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'credit_level_review',
      tableRow: {},
      isReviewApiError: true,

      // 还款计划
      viewRepayList: [],
      repayType: '',
      enumRepayType,
      enumRepayInterest: {
        0: '否',
        1: '是',
      },
      repayList: [],
      repayVisible: false,
      repayLoading: false,
      dialogMaxheight: 500,
      rowWidth: '170px',
      contract: {},
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'entrustContract']),
    isViewMode() {
      return this.viewMode
    },
    // || +this.relatedData.approval_register_status !== 0
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
    repayMonthType() {
      return +this.contract.repay_method === 1
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
  },
  watch: {
    relatedData: {
      handler: 'getData',
      deep: true,
      immediate: true,
    },
    entrustContract: {
      handler: function () {
        this.initContractByExist()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getRepayList(data = []) {
      this.repayList = data
    },
    initContractByExist() {
      if (!this.hasContract) {
        this.isReviewApiError = true
        return
      }
      this.isReviewApiError = false
      this.contract = { ...this.entrustContract }
      this.setByRelatedIfEmpty()
      this.repayType = this.contract.repay_method
    },
    setByRelatedIfEmpty() {
      ;['load_rate', 'reply_funds', 'load_years', 'gua_rate', 'approval_fee'].forEach(key => {
        if (!this.contract[key]) {
          this.contract[key] = this.relatedData[key]
        }
      })
    },
    async getData() {
      Promise.all([this.getWarrantFeeRecord(this.relatedId)])
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleDismiss() {
      this.$refs.repay.handleInit()
      this.$emit('dismiss', this.repayVisible)
    },
    handlePass() {
      if (this.isReviewApiError) {
        return this.$message.error('获取登记信息失败，请刷新重试！')
      }

      if (this.isBankOrg) {
        if (!this.validatorBank()) {
          return
        }
      } else {
        if (!this.validatorCredit()) {
          return
        }
      }

      this.onSave()
      this.saveWarrantFeeRecord(this.relatedId)
    },
    validatorBank() {
      const enumValid = {
        repay_method: '请选择还款付息方式',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },
    validatorCredit() {
      const enumValid = {
        // load_date: '请输入贷款时间'
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    onSave() {
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () => this.registerData(),
        })
        .then(() => {
          this.$message.success('登记成功！')
          this.$emit('success', true)

          this.$refs.repay.addRepayList()
          this.$emit('success', false)
          this.beforeClose()
        })
        .catch(() => this.$message.error(`登记失败，请重试！`))
    },

    registerData() {
      const PromiseArray = [
        this.$store.dispatch('updateEntrustContract', {
          id: this.contract.entrust_contract_id,
          data: {
            repay_method: this.contract.repay_method,
            gua_rate: this.contract.gua_rate || this.relatedData.gua_rate,
          },
        }),
      ]
      if (+this.relatedData.gua_type === 4 || +this.relatedData.gua_type === 2) {
        PromiseArray.push(
          this.$api.updateData(
            this.$serviceName,
            'customer_related',
            this.relatedData.customer_related_id,
            { loan_approval_status: 3 }
          )
        )
      }
      return Promise.all(PromiseArray)
    },

    // 还款计划
    showViewRepayList() {
      this.repayVisible = true
    },

    showRepayList() {
      if (this.repayList.length > 1) {
        // 之前修改的
        this.repayVisible = true
        return
      }
      if (!+this.contract.repay_method) {
        return this.$message.warning('请先选择还款设置')
      }
      // 不是按照贷款日期来计划开始时间
      // const startDate = this.repayStart ? new Date(this.repayStart) : ''
      // if (!startDate) {
      //   return this.$message.warning('请先填写贷款日期')
      // }
      const period = +this.contract.load_years || 0
      if (!period) {
        return this.$message.warning('没有用款期限')
      }
      this.repayVisible = true
    },
    onRepayClose() {
      this.repayVisible = false
    },
    onRepayTypeChange(val) {
      if (this.repayList.length < 2) {
        this.contract.repay_method = val
        return
      }
      this.repayType = this.contract.repay_method
      this.$confirm('已经有还款计划，更换还款设置后需要重新生成，确定修改？', '提示', {
        confirmButtonText: '确定修改',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$refs.repay.initRepayList()
          this.repayType = val
          this.contract.repay_method = val
        })
        .catch(() => {})
    },
    isLastMonthAtQuarter(payTime) {
      if (this.repayMonthType || !payTime) {
        return true
      }
      return (new Date(payTime).getMonth() + 1) % 3 === 0
    },
    getSums(list) {
      let [capitalSum, interestSum] = [0, 0]
      for (const item of list) {
        const capital = Number.parseFloat(item.capital)
        capitalSum += isNaN(capital) ? 0 : capital

        const interest = Number.parseFloat(item.interest)
        interestSum += isNaN(interest) ? 0 : interest
      }
      return [Math.round(capitalSum * 1e2) / 1e2, Math.round(interestSum * 1e2) / 1e2]
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.bg-gray {
  background-color: $gray-200;
}
.report-input-td {
  background-color: #ffe;
}
.auto-fill-icon {
  background-color: #ffe;
  color: $gray-500;
  line-height: 36px;
  overflow: hidden;
  cursor: pointer;
}
.text-center /deep/ .el-input__inner {
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.label-td {
  background-color: #f8f9fa;
}
.input-td-btn {
  border-radius: 0;
  border: none;
  margin-right: 1px;
}
.row-sum {
  background-color: $gray-100;
  padding-right: 20px;
  display: flex;
  flex-wrap: nowrap;
  .row-sum-td {
    flex: 1;
    padding: 0.5rem 0.25rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }
}
</style>
